package com.example.example.config;

import com.example.example.interceptor.TokenInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Slf4j
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private TokenInterceptor jwtTokenInterceptor;

    /**
     * 注册拦截器
     *
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册拦截器...");
        // 拦截所有请求, 放行 login 请求
        registry.addInterceptor(jwtTokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login");
    }
    
    /**
     * 配置异步请求处理选项
     * 替换默认的SimpleAsyncTaskExecutor为更适合生产环境的ThreadPoolTaskExecutor
     */
    @Override
    protected void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(30000); // 设置异步请求超时时间为30秒
        configurer.setTaskExecutor(mvcAsyncTaskExecutor());
    }
    
    /**
     * 创建并配置用于Spring MVC异步请求处理的线程池
     * 替代默认的SimpleAsyncTaskExecutor，更适合生产环境使用
     */
    @Bean
    public AsyncTaskExecutor mvcAsyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);       // 核心线程数
        executor.setMaxPoolSize(10);       // 最大线程数
        executor.setQueueCapacity(100);    // 队列容量
        executor.setThreadNamePrefix("mvc-async-"); // 线程名前缀
        executor.initialize();
        return executor;
    }
}
